package com.java.controller;


import com.java.entity.Blog;
import com.java.service.BlogService;
import com.java.utils.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author 博客Controller层
 * @create 2020-03-11 21:15
 */
@Controller
@RequestMapping("/blog")
public class BlogController {
    @Resource
    private BlogService blogService;

    @RequestMapping("/articles/{id}")
    public ModelAndView getBlog(@PathVariable("id") Integer id, HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView();
        Blog blog = blogService.getBlogById(id);
        modelAndView.addObject("blog",blog);
        blog.setClickHit(blog.getClickHit()+1);
        blogService.updateChick(blog);//更新点击量
        //获取关键字
        String keyWords = blog.getKeyWord();
        if(StringUtil.isNotEmpty(keyWords)){
            String arr[]=keyWords.split(" ");
            modelAndView.addObject("keyWords", StringUtil.filterWhite(Arrays.asList(arr)));
        }else{
            modelAndView.addObject("keyWords",null);
        }
        modelAndView.addObject("pageCode",this.getLastAndUpBlog(blogService.getLastBlog(blog.getId()),blogService.getNextBlog(blog.getId()),request.getServletContext().getContextPath()));
        modelAndView.addObject("mainPage","foreground/blog/view.jsp");
        modelAndView.addObject("pageTitle",blog.getTitle()+"java开源博客系统");
        modelAndView.setViewName("mainTemp");


        return  modelAndView;

    }


    public String getLastAndUpBlog(Blog lastBlog,Blog nextBlog,String projectContext){
       StringBuffer pageCode = new StringBuffer();
       if (Objects.isNull(lastBlog)){
           pageCode.append("<p>上一篇: 没有了</p>");
       }else {
           pageCode.append("<p>上一篇: <a href='"+projectContext+"/blog/articles/"+lastBlog.getId()+".html'>"+lastBlog.getTitle()+"</a> </p>");
       }
        if (Objects.isNull(nextBlog)){
            pageCode.append("<p>下一篇: 没有了</p>");
        }else {
            pageCode.append("<p>下一篇: <a href='"+projectContext+"/blog/articles/"+nextBlog.getId()+".html'>"+nextBlog.getTitle()+"</a> </p>");
        }

        return  pageCode.toString();
    }
}
